package com.yaorange.jk.utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author coach tam
 * @date 2017/11/6
 */
public class MailUtils {
    /**
     * 发送邮件
     * @param to  收件人邮箱地址
     * @param subject  主题
     * @param text  正文
     */
    public static void sendMail(String to,String subject,String text)
    {
        //1,准备配置信息
        Properties properties = new Properties();
        properties.put("mail.smtp.host","smtp.sina.com");
        properties.put("mail.smtp.auth","true");

        //2,获取和smtp服务器的会话
        Session session = Session.getInstance(properties);

        //3,构造message对象
        Message message = new MimeMessage(session);
        try {
        //4,设置发件人
        Address fromAddress = new InternetAddress("yaorange_mail@sina.com");

        message.setFrom(fromAddress);

        //5,设置收件人
        Address toAddress = new InternetAddress(to);

        message.setRecipient(Message.RecipientType.TO,toAddress);
        //6,设置标题
        message.setSubject(subject);

        //7,设置正文
//        message.setText(text);
        message.setContent(text,"text/html;charset=utf-8");


        //8,保存设置
//        message.saveChanges();

        //9,获取传输端口对象
        Transport transport = session.getTransport("smtp");

        //10,通过传输对象连接服务器
        transport.connect("smtp.sina.com","yaorange_mail@sina.com","yaorange201703");
        //10,通过传输端口对象发送
        transport.sendMessage(message,message.getAllRecipients());

        //11,关闭传输端口
        transport.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException();
        }
    }
}
